namespace SimpleWebServices.IO
{
    using System;
    using System.IO;
    using System.Xml.XPath;
    using SimpleWebServices.Data;

    public sealed class SerializationFile : IDisposable
    {
        private bool _disposed;

        public SerializationFile(object value)
            : this(value.Serialize())
        {
        }

        public SerializationFile(IXPathNavigable xml)
        {
            if (null == xml)
            {
                throw new ArgumentNullException("xml");
            }

            this.Info = new FileInfo((string)Token.New() + ".xml");
            using (FileStream file = File.Open(this.Info.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (StreamWriter writer = new StreamWriter(file))
                {
                    writer.Write(xml.CreateNavigator().OuterXml);
                }
            }

            this.Info.Refresh();
        }

        ~SerializationFile()
        {
            this.Dispose(false);
        }

        public FileInfo Info
        {
            get;
            private set;
        }

        public FileStream Open()
        {
            return File.Open(this.Info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    this.Info.Refresh();
                    if (this.Info.Exists)
                    {
                        File.Delete(this.Info.FullName);
                    }
                }

                this._disposed = true;
            }
        }
    }
}